package com.mby.controller;

import com.mby.entity.ChatGroup;
import com.mby.entity.CommonPics;
import com.mby.entity.Dealer;
import com.mby.service.IPushService;
import com.mby.service.IRongYunService;
import com.mby.utils.ExcelUtils;
import com.mby.utils.WebConstant;
import com.mongodb.*;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * Created by noah on 2018/7/5.
 */
@RestController
@RequestMapping("/report")
public class ReportController extends BaseController{

    /**
     * 服务直播间数据报表，编号 经销商 工单号 服务顾问 创建时间 车主姓名 品牌 车型 车牌 VIN 到店接车 预计交车 保养 质检及洗车 准备交车 结束时间
     * 参数：时间、工单号、经销商（名称、编码）、是否结束
     * get /live/report/live_detail
     */
    @GetMapping(value = "/live_detail")
    public void getLiveDetail(String startNo,String endNo,String dispatchingNo,String dealerId,Boolean isEnd,Integer pageNo,Integer pageSize){

        Map<String,String> dealerNames = new HashMap<>();
        String whereStr = "";
        if(StringUtils.isNotEmpty(currentUser().getDealerId())){
            whereStr = "{'id':'"+currentUser().getDealerId()+"'}";
        }else{
            if(StringUtils.isNotEmpty(dealerId)){
                whereStr = "{'id':'"+dealerId+"'}";
            }
        }
        List<Dealer> dealers = (List<Dealer>) mongoTool.findMany("id,cn",whereStr,"", Dealer.class);
        if(dealers.size() > 0){
            for(Dealer dealer : dealers){
                dealerNames.put(dealer.getId(),dealer.getCn().get("name").toString());
            }
        }

        whereStr = "";
        if(StringUtils.isNotEmpty(startNo)){
            startNo = startNo + " 00:00:01";
            whereStr = whereStr + "'createdAt>=':'"+startNo+"',";
        }
        if(StringUtils.isNotEmpty(endNo)){
            endNo = endNo + " 23:59:59";
            whereStr = whereStr + "'createdAt<=':'"+endNo+"',";
        }
        if(StringUtils.isNotEmpty(dispatchingNo)){
            whereStr = whereStr + "'dispatchingNo*':'"+dispatchingNo+"',";
        }
        if(StringUtils.isNotEmpty(currentUser().getDealerId())){
            whereStr = whereStr + "'dealerId':'"+currentUser().getDealerId()+"',";
        }else{
            if(StringUtils.isNotEmpty(dealerId)){
                whereStr = whereStr + "'dealerId':'"+dealerId+"',";
            }
        }
        if(isEnd != null){
            if(isEnd){
                whereStr = whereStr + "'deletedAt!':null,";
            }else{
                whereStr = whereStr + "'deletedAt':null,";
            }
        }
        if(whereStr.length() > 0){
            whereStr = "{" + whereStr.substring(0,whereStr.length()-1) + "}";
        }
        List<ChatGroup> groups = (List<ChatGroup>) mongoTool.findMany("",whereStr,"id",ChatGroup.class);
        List<ChatGroup> result = new ArrayList<>();
        Map<String,Object> resultMap = new HashMap<>();
        if(groups != null && pageNo != null && pageSize != null){
            ChatGroup chatGroup;
            pageNo = pageNo -1;
            int i = pageNo * pageSize;
            while(i >= pageNo * pageSize && i < (pageNo + 1) * pageSize && i < groups.size()){
                chatGroup = groups.get(i);
                result.add(chatGroup);
                i++;
            }
            resultMap.put("total",groups.size());
            resultMap.put("list",result);
            resultMap.put("dealerDic",dealerNames);
            respData(resultMap);
        }else{
            respData(groups);
        }
    }

    private static String[] title = {"编号","经销商","工单号","服务顾问","创建时间","车主姓名","品牌","车型","车牌","VIN","到店接车","预计交车","保养","质检及洗车","准备交车","结束时间"};
    /**
     * 服务直播间数据报表，编号 经销商 工单号 服务顾问 创建时间 车主姓名 品牌 车型 车牌 VIN 到店接车 预计交车 保养 质检及洗车 准备交车 结束时间
     * 参数：时间、工单号、经销商（名称、编码）、是否结束
     * get /live/report/live_detail
     */
    @GetMapping(value = "/live_detail/excel")
    public void getLiveDetailExcel(String startNo,String endNo,String dispatchingNo,String dealerId,Boolean isEnd){

        WritableWorkbook workbook = null;
        String file_name = WebConstant.CHATGROUP_DETAIL_PATH + "chatGroups.xls";
        File file = new File(file_name);

        Map<String,String> dealerNames = new HashMap<>();
        String whereStr = "";
        if(StringUtils.isNotEmpty(currentUser().getDealerId())){
            whereStr = "{'id':'"+currentUser().getDealerId()+"'}";
        }else{
            if(StringUtils.isNotEmpty(dealerId)){
                whereStr = "{'id':'"+dealerId+"'}";
            }
        }
        List<Dealer> dealers = (List<Dealer>) mongoTool.findMany("id,cn",whereStr,"", Dealer.class);
        if(dealers.size() > 0){
            for(Dealer dealer : dealers){
                dealerNames.put(dealer.getId(),dealer.getCn().get("name").toString());
            }
        }

        whereStr = "";
        if(StringUtils.isNotEmpty(startNo)){
            startNo = startNo + " 00:00:01";
            whereStr = whereStr + "'createdAt>=':'"+startNo+"',";
        }
        if(StringUtils.isNotEmpty(endNo)){
            endNo = endNo + " 23:59:59";
            whereStr = whereStr + "'createdAt<=':'"+endNo+"',";
        }
        if(StringUtils.isNotEmpty(dispatchingNo)){
            whereStr = whereStr + "'dispatchingNo*':'"+dispatchingNo+"',";
        }
        if(StringUtils.isNotEmpty(currentUser().getDealerId())){
            whereStr = whereStr + "'dealerId':'"+currentUser().getDealerId()+"',";
        }else{
            if(StringUtils.isNotEmpty(dealerId)){
                whereStr = whereStr + "'dealerId':'"+dealerId+"',";
            }
        }
        if(isEnd != null){
            if(isEnd){
                whereStr = whereStr + "'deletedAt!':null,";
            }else{
                whereStr = whereStr + "'deletedAt':null,";
            }
        }
        if(whereStr.length() > 0){
            whereStr = "{" + whereStr.substring(0,whereStr.length()-1) + "}";
        }
        List<ChatGroup> groups = (List<ChatGroup>) mongoTool.findMany("",whereStr,"",ChatGroup.class);

        if(groups.size() > 0){
            try {
                workbook = Workbook.createWorkbook(file);
                WritableSheet ws = workbook.createSheet("likes",0);
                putRowTitle(ws,0,title); int rows; int count = 0;
                for(ChatGroup chatGroup : groups) {
                    rows = 0;
                    putRowData(ws, count + 1, rows++, String.valueOf(count+1)); //编号
                    putRowData(ws, count + 1, rows++, dealerNames.get(chatGroup.getDealerId())); //经销商
                    putRowData(ws, count + 1, rows++, chatGroup.getDispatchingNo()); //工单号
                    putRowData(ws, count + 1, rows++, chatGroup.getAgentName()); //服务顾问
                    putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getCreatedAt())); //创建时间
                    putRowData(ws, count + 1, rows++, chatGroup.getCustomerName()); //车主姓名

                    if(chatGroup.getBrandId() == 1){
                        putRowData(ws, count + 1, rows++, "捷豹"); //品牌
                    }else{
                        putRowData(ws, count + 1, rows++, "路虎"); //品牌
                    }

                    putRowData(ws, count + 1, rows++, chatGroup.getModel()); //车型
                    putRowData(ws, count + 1, rows++, chatGroup.getPlateNo()); //车牌
                    putRowData(ws, count + 1, rows++, chatGroup.getVin()); //VIN

                    if(chatGroup.getArrivedDate() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getArrivedDate())); //到店接车
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //到店接车
                    }

                    if(chatGroup.getEstHandoverDate() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getEstHandoverDate())); //预计交车
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //预计交车
                    }

                    if(chatGroup.getMaintainedAt() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getMaintainedAt())); //保养
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //保养
                    }

                    if(chatGroup.getQualityCheckDate() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getQualityCheckDate())); //质检及洗车
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //质检及洗车
                    }

                    if(chatGroup.getQualityCheckDate() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(new Date(chatGroup.getQualityCheckDate().getTime() + 2400000))); //准备交车
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //准备交车
                    }

                    if(chatGroup.getDeletedAt() != null){
                        putRowData(ws, count + 1, rows++, ymdhms.format(chatGroup.getDeletedAt())); //结束时间
                    }else{
                        putRowData(ws, count + 1, rows++, "-"); //结束时间
                    }
                    count ++;
                }
                workbook.write();
                workbook.close();
                ExcelUtils.download(WebConstant.CHATGROUP_DETAIL_PATH,"chatGroups.xls");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        respData(resultMap);
    }
}
